/**
 * Created by ruiyuan on 15-9-22.
 */
'use strict';

/* App Module */

var marketApp = angular.module('marketApp', ['ngRoute', 'ngResource', 'marketFilters']);
var params = {};
var tempArray = window.location.search.split('?');
if (tempArray.length == 2) {
    var parts = tempArray[1].split('&');
    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}
/*  宝宝树66小区二次改造    mod   zhangm.wedo  20170719   start   */
//var host = 'localhost:3000';
/*  宝宝树66小区二次改造    mod   dayu.wedo  20170723   start   */

/* 宝宝树66小区三次改造 120.55.118.234 地址替换为app.66xiaoqu.com mod wangcan 20170928 start */
// var host = '120.55.118.234:3000';
// var host = 'app.h2oprint.com';
// var host = 'app.66xiaoqu.com';
var host = 'app-66xiaoqu.babytree.com';
/* 宝宝树66小区三次改造 120.55.118.234 地址替换为app.66xiaoqu.com mod wangcan 20170928 end */

//var host = 'app.h2oprint.com';
/*  宝宝树66小区二次改造    mod   dayu.wedo  20170723   end   */
/*  宝宝树66小区二次改造    mod   zhangm.wedo  20170719   end   */
marketApp.controller('GoodsListCtrl', ['$scope', 'GoodList', 'QueryTerms', 'GoodsCategory', 'Banner', 'ClickLog', 'SaleRecord',
    function ($scope, GoodList, QueryTerms, GoodsCategory, Banner, ClickLog, SaleRecord) {

        $scope.goodsSortOptions = [
            {key : "default", name : "默认排序"},
            {key : "location", name : "离我最近"},
            {key : "priceHighToLow", name : "价格由高到低"},
            {key : "priceLowToHigh", name : "价格由低到高"}
        ];

        $(".classify").on("click",function(){
            if(new RegExp("arrow_up.png").test($(".classify img")[0].src)){
                $(".classify img").attr("src","./images/arrow_down.png");
                $("#classify").removeClass("selected");
                $("#select_list").css("display","none");
                return;
            }
            $("#classify")[0].className = "selected";
            $(".classify img").attr("src","./images/arrow_up.png");
            $("#select_list").css("display","block");
        });

        $("#select_list li").on("click",function(){

            $(this).siblings().removeClass("selected");
            $(this).addClass("selected");
            $("#classify").text($(this).text());
            $("#classify").removeClass("selected");
            $("#select_list").css("display","none");
            $(".classify img").attr("src","./images/arrow_down.png");

            $scope.sort = this.dataset.val;
            $scope.ts = 0;  // page number
            getNewData(true);
        });

            /* =================================== SALE STUFF =================================== */
        var startTime = moment().startOf('week').add(6, 'day').add(18, 'hour');
        var endTime = moment().startOf('week').add(6, 'day').add(22, 'hour');
        //$showSale();
        function $showSale() {
            if (moment().isBetween(startTime, endTime)) {
                if (localStorage.getItem('saleFlag') == null) {
                    $('#sale_url').attr('href', "http://" + host + "/market/recommend.html" + window.location.search);
                    $disableScroll();
                    $('#sale').css('display', 'block');
                }
            } else {
                localStorage.removeItem('saleFlag');
            }
        }

        var time = startTime.toDate().getTime() - new Date().getTime();
        //setTimeout($showSale, time);

        $scope.gotoSale = function () {
            localStorage.setItem('saleFlag', 1);
            $('#sale').css('display', 'none');
            $enableScroll();
        };
        $scope.hideSale = function () {
            document.getElementById('reged').style.display = 'none';
        };
        $scope.saveRecord = function () {
            if ($scope.goods != null && !$scope.goods.isRecord) {
                SaleRecord.save({}, {goodsId: $scope.goods.objId, goodsTitle: $scope.goods.title});
                $scope.goods.isRecord = true;
            }
            $scope.hideSale();
        };

        /* =================================== BANNER STUFF =================================== */
        $scope.bannerList = Banner.getBanner(function (result) {
            var lenn = 0;
            var str = "";
            if(result.data != null && result.data != undefined) {
                lenn = result.data.length;
                for (var i = 0; i < result.data.length; i++) {
                    var url = "";
                    if (result.data[i].url.indexOf('?') > 0) {
                        url = result.data[i].url + "&token=" + params.token + "&deviceId=" + params.deviceId + '&clickSource=701';
                    } else {
                        url = result.data[i].url + "?token=" + params.token + "&deviceId=" + params.deviceId + '&clickSource=701';
                    }
                    str += '<div class="swiper-slide"><a href="' + url + '"><img src="' + result.data[i].imageURL + '"></a></div>';
                }
            }
            $('.swiper-wrapper').html(str);

            var swiperClass = '.swiper-container';

            var swiperBanner = new Swiper(swiperClass, {
                pagination: '.pagination',
                paginationClickable: true,
                loop: true
            });

            if (lenn > 0) {
                $(swiperClass).css('padding', '3px 0 5px 0');
                $(swiperClass).css('background-color', '#eeebeb');
            } else {
                $(swiperClass).css('visibility', 'hidden');
            }

            if (lenn > 1) {
                setInterval(function () {
                    swiperBanner.swipeNext();
                }, 4000);
            }

            $('.swiper-slide').click(function () {
                ClickLog.save({}, {type: 40, typeDesc: '集市banner', 'userId': params.token})
            });

            $('.loading-pop').hide();

        }, function (err) {
            $('#load_img').hide();
            $('#reload').show()
        });

        /* =================================== 页面 =================================== */

        var no_goodsText = "空空的，赶紧按下面“+”号发布闲置吧～"
        var no_servicesText = "服务版块近期即将开放，敬请期待！"
        var no_localText = "空空的，赶紧按下面“+”号发布内容吧～"

        $scope.no_goodsText = "";


        $scope.goodsImgW = ($(window).width()) * 0.3 + 'px';
        $scope.goodsImgH = ($(window).width()) * 0.3 + 'px';

        $scope.rangeList = [
            {name: '同城', value: 'city', img: 'images/range_city.png'},
            //{name: '周边小区', value: 'around'},
            {name: '本小区', value: 'only', img: 'images/range_only.png'},
            {name: '全国', value: 'all', img: 'images/range_all.png'}
        ];
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   start   */
        // $scope.sortList = [
        //     {name: '最新发布', value: 'release', img: 'images/sort_release.png'},
        //     {name: '智能排序', value: 'smart', img: 'images/sort_smart.png'},
        //     {name: '距离最近', value: 'location', img: 'images/sort_location.png'},
        //     {name: '免费优先', value: 'priceLowToHigh', img: 'images/sort_free.png'},
        //     {name: '城市排序', value: 'city', img: 'images/sort_city.png'}
        // ];

        /* 获数据的parameters  */
        $scope.goodsList = [];   // data
        $scope.ts = 0;          // page number
        $scope.type = 0;        // 1:非免费，2:免费
        $scope.itemType = 1;   // 0: 全部, 1:闲置，2:服务  // default: goods
        $scope.range = $scope.rangeList[0].value; // default: city

        // $scope.sort = $scope.sortList[2].value;   // default: location // 旧
        $scope.sort = $scope.goodsSortOptions[0].key;   // default
        /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   end   */

        /* 逻辑 */

        var sessionItemType = sessionStorage.getItem("itemType");
        var sessionColumn = sessionStorage.getItem("column");

        $scope.clickGoods = function () {
            $linkActive(1);
            $scope.itemType = 1;
            $scope.ts = 0;
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   start   */
            // $scope.sort = $scope.sortList[4].value;    // 城市排序 // 旧
            $scope.sort = $scope.goodsSortOptions[0].key;   // default
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   end   */
            $scope.range = $scope.rangeList[2].value;   // 全国
            sessionStorage.setItem('column', "goods");
            getNewData(true);
        };

        <!--  宝宝树66小区二次改造    del   张秘  20170718   start -->
 /*       $scope.clickServices = function () {
            $linkActive(2);
            $scope.itemType = 2;
            $scope.ts = 0;
            //$scope.range = $scope.rangeList[0].value;
            $scope.sort = $scope.sortList[2].value;     // 距离排序
            $scope.range = $scope.rangeList[2].value;   // 全国
            sessionStorage.setItem('column', "services");
            getNewData(true);
        };*/
        <!--  宝宝树66小区二次改造    del   张秘  20170718   end -->

        $scope.clickLocal = function () {
            <!--  宝宝树66小区二次改造    mod   张秘  20170718   start -->
            $linkActive(2);
            <!--  宝宝树66小区二次改造    mod   张秘  20170718   end -->
            $scope.itemType = 0;
            $scope.ts = 0;
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   start   */
            // $scope.sort = $scope.sortList[0].value;   // (最新发布)
            $scope.sort = $scope.goodsSortOptions[0].value;   // (最新发布)
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170904   end   */
            $scope.range = $scope.rangeList[1].value;
            sessionStorage.setItem('column', "local");
            getNewData(true);
        };

        if (params.itemType && params.itemType != sessionItemType) {
            $scope.itemType = parseInt(params.itemType);
            if ($scope.itemType == 2) {
                $scope.clickServices();
            } else if ($scope.itemType == 0) {
                $scope.clickLocal();
            } else {
                $scope.clickGoods();
            }
            sessionStorage.setItem('itemType', $scope.itemType);
        } else {
            if (sessionColumn == "local") {
                $scope.clickLocal();
            } else if (sessionColumn == "services") {
                $scope.clickServices();
            } else {
                $scope.clickGoods();
            }
        }

        $(".wrapper").on("swipeleft", swipeLeftHandler);
        $(".wrapper").on("swiperight", swipeRightHandler);

        function swipeLeftHandler(event) {
            if ($scope.itemType == 1) {
                $scope.clickServices();
            } else if ($scope.itemType == 2) {
                $scope.clickLocal();
            }
        }

        function swipeRightHandler(event) {
            if ($scope.itemType == 0) {
                $scope.clickServices();
            } else if ($scope.itemType == 2) {
                $scope.clickGoods();
            }
        }

        /*

         $scope.range = sessionStorage.getItem('range') ? JSON.parse(sessionStorage.getItem('range')).value : $scope.rangeList[1].value;
         $scope.rangeName = sessionStorage.getItem('range') ? JSON.parse(sessionStorage.getItem('range')).name : $scope.rangeList[0].name;
         $scope.defaultRange = sessionStorage.getItem('range') ? null : '范围';

         $scope.category = sessionStorage.getItem('category') ? JSON.parse(sessionStorage.getItem('category')).objId : 'all';
         $scope.categoryName = sessionStorage.getItem('category') ? JSON.parse(sessionStorage.getItem('category')).name : '闲置(全部)';
         $scope.defaultCategory = sessionStorage.getItem('category') ? null : '闲置分类';

         $scope.servicesCategory = sessionStorage.getItem('servicesCategory') ? JSON.parse(sessionStorage.getItem('servicesCategory')).value : 'all';
         $scope.servicesCategoryName = sessionStorage.getItem('servicesCategory') ? JSON.parse(sessionStorage.getItem('servicesCategory')).name : '服务(全部)';
         $scope.defaultServicesCategory = sessionStorage.getItem('servicesCategory') ? null : '服务分类';

         $scope.categoryList = [{name: '闲置(全部)', objId: 'all', img: 'images/category_all.png'}];
         $scope.servicesCategoryList = [{name: '服务(全部)', objId: 'all', img: 'images/category_all.png'}];
         GoodsCategory.getGoodsCat(function (result) {
         $scope.categoryList = $scope.categoryList.concat(result.data);
         });
         GoodsCategory.getServicesCat(function (result) {
         $scope.servicesCategoryList = $scope.servicesCategoryList.concat(result.data);
         });

         //$scope.sort = sessionStorage.getItem('sort') ? JSON.parse(sessionStorage.getItem('sort')).value : 'release';
         //$scope.sortName = sessionStorage.getItem('sort') ? JSON.parse(sessionStorage.getItem('sort')).name : '最新发布';
         //$scope.defaultSort = sessionStorage.getItem('sort') ? null : '排序';
         */

        var isMore = true;//判断是否有更多数据
        var isfinish = true;//isfinish判断每次数据是否加载完成，完成了才可进行下一次加载
        var isFlag = false;

        //获取数据hv
        function getNewData(flag) {
            if (flag)
                $('.loading-pop').show();
            GoodList.get({
                ts: $scope.ts,
                // type: $scope.type, // 免费,非免费
                // itemType: $scope.itemType,
                range: $scope.range,
                //category: $scope.itemType == 1 ? $scope.category : $scope.servicesCategory,
                sort: $scope.sort // 排序
            }, function (result) {
                if(result.data != null && result.data != undefined) {
                    $scope.ts = result.data.ts;

                    //console.log("TS", $scope.ts)
                    if (flag) {
                        $scope.goodsList = result.data.list;
                    } else {
                        $scope.goodsList = $scope.goodsList.concat(result.data.list);
                    }
                }
                $nogoodsDisplay($scope.goodsList.length == 0);
                // if ($scope.itemType == 2) {
                //     $scope.no_goodsText = no_servicesText;
                // } else if ($scope.itemType == 0) {
                //     $scope.no_goodsText = no_localText;
                // } else {
                //     $scope.no_goodsText = no_goodsText;
                // }

                isfinish = true;
                isMore = true;
                if (result.data != null && result.data != undefined && result.data.list.length == 0) {
                    isMore = false;
                    $loadingDonePopup();
                }
                $('.loading-pop').hide();
                $(".loadingMore").html('');
            });
        }

        var count = 0;
        //2、滚动加载更多
        $('.wrapper').scroll(function () {
            if (params.type == 'ios') {
                $iosScrollTop();
            }

            var show = count == 0 ? 1 : $('.categorylist-w').offset().top;

            count++;
            var firstLoad = show > 0;
            //$categoryVisibility(firstLoad);
            if (!isMore){
                var contentHeight = $(".wrapper")[0].scrollHeight;
                var h = $(".wrapper").height();
                if ((contentHeight - h - $(this).scrollTop()) <= 10) {
                    $loadingDonePopup();
                }
            }
            else if (isMore && isfinish) {
                var contentHeight = $(".wrapper")[0].scrollHeight;
                var h = $(".wrapper").height();
                if ((contentHeight - h - $(this).scrollTop()) <= 75) {
                    isfinish = false;
                    $(".loadingMore").html('<img src="images/loading.gif" />正在加载');
                    //此处为加载下一条的方法
                    if (!firstLoad)
                        getNewData(false);
                    else
                        $scrollTop();
                }
            }
        }).scroll();

        $scope.reload = function () {
            document.location.reload()
        };
        /*
         //筛选确定
         $scope.rangeClick = function (range) {
         $hideLayout(0);
         $scope.defaultRange = null;
         $scope.ts = 0;
         $scope.rangeName = range.name;
         $scope.range = range.value;
         sessionStorage.setItem('range', JSON.stringify(range));
         getNewData(true);

         ClickLog.save({}, {type: 81, typeDesc: '集市范围点击', 'userId': params.token, ext: range.name})
         };

         //闲置分类点击
         $scope.categoryClick = function (category) {
         $hideLayout(1);
         $scope.defaultCategory = null;
         $scope.itemType = 1;
         $scope.categoryName = category.name;
         $scope.category = category.objId;
         $scope.ts = 0;
         sessionStorage.setItem('category', JSON.stringify(category));
         getNewData(true);

         ClickLog.save({}, {type: 82, typeDesc: '闲置分类点击', 'userId': params.token, ext: category.name})
         };

         //服务分类点击
         $scope.servicesCategoryClick = function (item) {
         $hideLayout(2);
         $scope.defaultServicesCategory = null;
         $scope.itemType = 2;
         $scope.servicesCategoryName = item.name;
         $scope.servicesCategory = item.objId;
         $scope.ts = 0;
         sessionStorage.setItem('servicesCategory', JSON.stringify(item));
         getNewData(true);

         ClickLog.save({}, {type: 84, typeDesc: '服务分类点击', 'userId': params.token, ext: item.name})
         };

         ////排序点击
         //$scope.sortClick = function (sort) {
         //    $hideLayout(2);
         //    $scope.defaultSort = null;
         //    $scope.sortName = sort.name;
         //    $scope.sort = sort.value;
         //    $scope.ts = 0;
         //    sessionStorage.setItem('sort', JSON.stringify(sort));
         //    getNewData(true);
         //
         //    ClickLog.save({}, {type: 83, typeDesc: '集市排序点击', 'userId': params.token, ext: sort.name})
         //};
         */

        /*
         //获取热门搜索分类
         QueryTerms.get(function (result) {
         $('.sub').hide();
         $scope.hotTerms = result.data;
         $scope.hotTerms.push({name: '免费', value: 2, type: 4, img: 'temp/index_temp4.png'});
         $scope.hotTerms.push({name: '本小区', value: 'only', type: 1, img: 'temp/index_temp5.png'});
         $scope.hotTerms.push({name: '周边小区', value: 'around', type: 1, img: 'temp/around.png'});
         });

         //热门分类点击
         $scope.clickHotTerm = function (term) {
         $scrollTop();
         $scope.ts = 0;
         switch (term.type) {
         case 1:
         $scope.rangeName = term.name;
         $scope.range = term.value;
         break;
         case 2:
         $scope.categoryName = term.name;
         $scope.category = term.value;
         break;
         case 3:
         $scope.sortName = term.name;
         $scope.sort = term.value;
         break;
         case 4:
         $scope.type = term.value;
         break;
         }
         getNewData(true);
         };
         */

        //去二手详情
        $scope.goToDetail = function (goods) {

            if ((!moment().isBetween(startTime, endTime)) && goods.saleNumber != null) {
                $('#saleRecordMsg').text(goods.isRecord ? '已标注' : '到时通知我');
                $('#reged').css('display', 'block');
                $scope.goods = goods;
            } else {
                window.location.href = "detail.html" + window.location.search + '&goodsId=' + goods.objId + '&createdBy=' + goods.createdBy + '&clickSource=702';
            }
        };

        $scope.goodsSortChangeAction = function () {
            $scope.sort = $scope.goodsSortOption;
            getNewData(false);
        }

    }
]);


marketApp.factory('Banner', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/market/banners/' + params.token + '/' + params.deviceId, {},
        {
            getBanner: {
                method: 'GET',
                timeout: 10000
            }
        }
    )
}]);

marketApp.factory('GoodList', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/market/goods/list/:ts/' + params.token + '/' + params.deviceId, {});
}]);

marketApp.factory('QueryTerms', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/market/goods/hotQueryTerms/' + params.token + '/' + params.deviceId, {})
}]);

marketApp.factory('GoodsCategory', ['$resource', function ($resource) {
    var url = 'http://' + host + '/rest/v1.0/market/goods/categoryList/' + params.token + '/' + params.deviceId;
    return {
        getGoodsCat: function (callback) {
            var res = $resource(url, {});
            res.get({itemType: 1}, callback);
        },
        getServicesCat: function (callback) {
            var res = $resource(url, {});
            res.get({itemType: 2}, callback);
        }
    }
}]);

marketApp.factory('ClickLog', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/appLog/clickAcquisition/' + params.deviceId, {})
}]);

marketApp.factory('SaleRecord', ['$resource', function ($resource) {
    return $resource('http://' + host + '/rest/v1.0/market/saleRecord/' + params.token + '/' + params.deviceId, {})
}]);
